package geektime.concurrent.part1;

/**
 * 模拟volatile在线程中起的作用
 */
public class VolatileTest {
//    private static boolean val = true;
    private static volatile boolean val = true;

    public static void main(String[] args) {
        new VolatileTest().new FirstThread().start();
        new VolatileTest().new SecondThread().start();
    }

    class FirstThread extends Thread {
        @Override
        public void run() {
            while (true) {
                if (val) {
                    System.out.println("Running: firstThread");
                    val = false;
                }
            }
        }
    }

    class SecondThread extends Thread {
        @Override
        public void run() {
            while (true) {
                if(!val) {
                    System.out.println("Running: secondThread");
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    val = true;
                }
            }
        }
    }
}


